<template>
	<view>
		<!-- use-chat-record-mode：开启聊天记录模式 -->
		<!-- use-virtual-list：开启虚拟列表模式 -->
		<!-- cell-height-mode：设置虚拟列表模式高度不固定 -->
		<!-- safe-area-inset-bottom：开启底部安全区域适配 -->
		<!-- bottom-bg-color：设置slot="bottom"容器的背景色，这里设置为和chat-input-bar的背景色一致 -->
		<z-paging 
			ref="paging" 
			v-model="talkList" 
			use-chat-record-mode 
			cell-height-mode="dynamic"
			safe-area-inset-bottom 
			bottom-bg-color="#f8f8f8" 
			@keyboardHeightChange="keyboardHeightChange" 
		>
			<!-- style="transform: scaleY(-1)"必须写，否则会导致列表倒置！！！ -->
			<view style="transform: scaleY(-1)" v-for="(item,index) in talkList" :key="index">
				<chat-item :item="item"></chat-item>
			</view>
			<!-- 底部聊天输入框 -->
			<template #bottom>
				<chat-input-bar ref="inputBar" @send="send" @handleOpen="handleopen" @startVoiceInput="startVoiceInput" />
			</template>
		</z-paging>

		<u-top-tips ref="uTips"></u-top-tips>
		
		<!-- 聊天设置组件 -->
		<chat-settings 
			:model-list="modelList" 
			:current-model="currentModel" 
			:enable-web-search="enableWebSearch"
			:show-clear-chat="talkList && talkList.length > 1"
			@clearChat="handleClearChat"
			@selectModel="handleSelectModel"
		/>
		
		<!-- 语音录制组件 -->
		<voice-recorder ref="voiceRecorder" @voiceResult="handleVoiceResult" />
		
		<!-- 消息服务组件 -->
		<chat-message-service ref="messageService" @showTip="showTip" :enableWebSearch="enableWebSearch"  />
	</view>
</template>

<script>
import chatInputBar from '@/components/chat-input-bar/chat-input-bar.vue'
import chatItem from '@/components/chat-item/chat-item.vue'
import userModel from '@/components/user-model/user-model.vue'
import chatSettings from '@/components/chat-settings/chat-settings.vue'
import voiceRecorder from '@/components/voice-recorder/voice-recorder.vue'
import chatMessageService from '@/components/chat-message-service/chat-message-service.vue'

export default {
	components: {
		chatInputBar,
		chatItem,
		userModel,
		chatSettings,
		voiceRecorder,
		chatMessageService
	},
	data() {
		return {
			talkList: [],
			content: '',
			currentModel: 'gpt-4',
			modelList: [],
			enableWebSearch: false, // 联网搜索开关状态
			typingInterval: 50,
		}
	},
	async onLoad(options) {
		// 处理传入的模式参数
		if (options.mode === 'web') {
			this.enableWebSearch = true
		}
		// 初始化数据
		await this.initData();
	},
	methods: {
		// 初始化数据
		async initData() {
			// 获取模型列表
			const modelData = await this.$refs.messageService.getModelList();
			this.modelList = modelData.modelList;
			this.currentModel = modelData.currentModel;
			
			// 获取历史消息
			const historyMessages = await this.$refs.messageService.getHistoryMsg(this.currentModel, this.modelList);
			this.$refs.paging.complete(historyMessages);
		},
		
		// 显示提示
		showTip(options) {
			this.$refs.uTips.show(options);
		},
		
		// 监听键盘高度改变
		keyboardHeightChange(res) {
			this.$refs.inputBar.updateKeyboardHeightChange && this.$refs.inputBar.updateKeyboardHeightChange(res);
		},
		
		// 处理用户面板打开
		handleopen() {
			this.$refs.userModel.open('base');
		},
		
		// 发送消息
		send(msg) {
			const sent = this.$refs.messageService.send(msg, this.talkList, this.currentModel, this.modelList);
			if (sent) {
				this.$refs.inputBar.setMsg('');
				this.$forceUpdate();
			}
		},
		
		// 开始语音输入
		startVoiceInput(isStart, isCancel) {
			this.$refs.voiceRecorder.startVoiceInput(isStart, isCancel);
		},
		
		// 处理语音识别结果
		handleVoiceResult(text) {
			console.log('handleVoiceResult',text);
			
			this.send(text);
			// // 将识别结果设置到输入框
			// this.$refs.inputBar.setMsg(text);
			
			// // 如果识别成功自动发送消息
			// if (text.trim().length > 0) {
			// 	setTimeout(() => {
					
			// 	}, 300);
			// }
		},
		
		// 清除聊天记录
		async handleClearChat() {
			const success = await this.$refs.messageService.clearChatHistory();
			if (success) {
				// 清空本地聊天列表
				this.talkList = [];
				// 重新获取历史消息（如果有的话）
				this.initData();
			}
		},
		
		// 选择模型
		async handleSelectModel(model) {
			// 如果选择的是当前模型，不执行任何操作
			if (this.currentModel === model) return;
			
			const result = await this.$refs.messageService.changeModel(model, this.modelList);
			if (result.success) {
				// 更新当前模型
				this.currentModel = model;
				
				// 更新所有机器人消息的模型名称
				this.talkList.forEach(item => {
					if(item.type === 0) {
						item.modelName = result.modelName;
					}
				});
				
				// 强制更新视图
				this.$forceUpdate();
			}
		},
	}
}
</script>

<style lang="scss">
page {
	background-color: #FFFFFF;
	font-size: 28rpx;
	box-sizing: border-box;
	color: #333;
	letter-spacing: 0;
	word-wrap: break-word;
}
</style>